import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_API, // url = base url + request url
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // 判断token 存在
        if (getToken()) {
            config.headers['Authorization'] = getToken()
        }

        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        // 不等于200接口处理
        if (res.code !== 200) {
            ElMessage({
                message: res.msg || 'Error',
                type: 'error',
                duration: 5 * 1000
            })

            return Promise.reject(res)
        } else {
            return res
        }
    },
    error => {
        if (error.code != "ECONNABORTED") {
            if (error.response.data.code == 401) {
                store.dispatch('user/logout').then(() => {
                    location.reload()
                })
            }
        }

        ElMessage({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
